package cn.itcast.service.Impl;

import cn.hutool.core.date.DateUtil;
import cn.itcast.dto.ChatDTO;
import cn.itcast.service.ChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

/**
 * @author GY
 * @version V1.0
 * @date 2025-04-20 21:09
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ChatServiceImpl implements ChatService {

    private final ChatClient chatClient;
    private final VectorStore vectorStore;

    @Override
    public String chat(String question, String sessionId) {
        return "";
    }

    @Override
    public Flux<String> streamChat(ChatDTO chatDTO) {
        // 创建搜索请求，用于搜索相关文档
        var searchRequest = SearchRequest.builder()
                .query(chatDTO.getQuestion()) // 设置查询条件
                .topK(3) // 设置最多返回的文档数量
                .build();

        return chatClient.prompt()
                .system(prompt -> prompt.param("now", DateUtil.now()))
                .advisors(advisor -> advisor.advisors(new QuestionAnswerAdvisor(vectorStore, searchRequest)) // 设置RAG的Advisor
                        .param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatDTO.getSessionId()))
                .user(chatDTO.getQuestion())
                .stream()
                .content()
                // 在流结束时添加结束标记
                .concatWith(Flux.just("[END]"));
    }
}
